package com.usts.edu.list;

/**
 * Created by Guanzhong Hu
 * Date :2019/12/27
 * Description : 顺序表实现
 * Version :1.0
 */
public class SqList implements Ilist {

    private Object[] listElem;

    private int curlen;

    public SqList( int maxLen) {
       listElem = new Object[maxLen];// 初始化最大空间
        this.curlen = 0; // 初始化0
    }

    @Override
    public void clear() {
        curlen = 0;
    }

    @Override
    public boolean isEmpty() {
        return curlen == 0;
    }

    @Override
    public int length() {
        return curlen;
    }

    @Override
    public Object get(int i) throws Exception {

        if(i<0 ||i>curlen-1) //如果越界或者小于0则不存在
            throw new Exception("第"+i+"个元素不存在");
        return listElem[i];
    }

    @Override
    public void insert(int i, Object x) throws Exception {
        if (curlen == listElem.length) throw new Exception("线性表已满");
        if(i<0 ||i>listElem.length) throw new Exception("插入位置不合法");
        for (int j = curlen; j > i; j--) {
            listElem[j] = listElem[j-1];
        }
        listElem[i] = x; // 位置空出来则存储
        curlen++;
    }

    @Override
    public void remove(int i) throws Exception{
        if(i<0 ||i>curlen-1) throw new Exception("删除位置不合法");
        for (int j = i; j<curlen-1;j++){
            listElem[j] = listElem[j+1];
        }
        listElem[length()-1] = null; // 将末尾置空
        curlen --;
    }

    @Override
    public int indexOf(Object x) {
        int index = 0;
        while (index < curlen && !listElem[index].equals(x))// 依次遍历，如果比较相等则判断为false跳出循环
            index++;
        if (index<curlen) return index;

        return -1; // -1表示不存在
    }

    @Override
    public void display() {
        if (curlen==0) System.out.println("线性表为空！");
       for (int i = 0; i < listElem.length ; i++) {
            System.out.print("index:"+i+"  value:"+listElem[i]+"\t");
        }
    }
}
